<!--  -->
<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
         
          <el-button type="danger" @click="allDelete" class="allDelete">批量删除</el-button>
          <el-tree
            show-checkbox
            ref="catTree"
            node-key="id"
            :data="goodsCategories"
            :props="defaultProps"
            :expand-on-click-node="false"
            :draggable="draggable"
            accordion
            @node-click='nodeClick'
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  v-if="node.level < 2"
                  type="text"
                  size="mini"
                  @click="() => append(data)"
                >
                  添加
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="() => edit(data)"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="node.childNodes.length == 0"
                  type="text"
                  size="mini"
                  @click="remove(node,data)"
                >
                  删除
                </el-button>
              </span>
            </span>
          </el-tree>
        </el-col>
        <el-col :span="18">
          <div class="mod-config">
          <el-form :inline="true" :model="dataForm" @keyup.enter.native="getAttrList()">
            <el-form-item>
              <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="getAttrList()">查询</el-button>
              <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
              <el-button  type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
            </el-form-item>
          </el-form>
          <el-table
            :data="dataList"
            border
            @selection-change="selectionChangeHandle"
            style="width: 100%;">
            <el-table-column
              type="selection"
              header-align="center"
              align="center"
              width="50">
            </el-table-column>
            <el-table-column
              prop="attrGroupId"
              header-align="center"
              align="center"
              label="分组id">
            </el-table-column>
            <el-table-column
              prop="attrGroupName"
              header-align="center"
              align="center"
              label="组名">
            </el-table-column>
            <!-- <el-table-column
              prop="sort"
              header-align="center"
              align="center"
              label="排序">
            </el-table-column> -->
            <el-table-column
              prop="descript"
              header-align="center"
              align="center"
              label="描述">
            </el-table-column>
            <el-table-column
              prop="catelogId"
              header-align="center"
              align="center"
              label="所属分类">
            </el-table-column>
            <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              width="150"
              label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="relationHandle(scope.row.attrGroupId)">关联</el-button>
                <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.attrGroupId,scope.row)">修改</el-button>
                <el-button type="text" size="small" @click="deleteHandle(scope.row.attrGroupId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
          <!-- 弹窗, 新增 / 修改 -->
          <GroupAddUpdate v-if="addOrUpdateVisible"  @updatedata="getAttrList" ref="addOrUpdate"></GroupAddUpdate>
        </div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加分类弹出框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="category">
        <el-form-item label="分类名称" >
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item v-if="category.catLevel === 2 && dialogType=== 'edit'" label="数量" >
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item> -->
        <el-form-item  v-show="category.catLevel === 2 && dialogType=== 'edit' " label="图标" >
          <img :src="category.icon" alt="" width="70px" height="70px">
          <OssUpload v-model="category.icon"></OssUpload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 关联弹框 -->
    <el-dialog
     
      :close-on-click-modal="false"
      :visible.sync="dialogTableVisible">
      <el-button type="primary" @click="addRelation()" >新增关联</el-button>
       <el-table :data="brandCategoryList" highlight-current-row  border>
        <el-table-column
        type="index"
         label="#"
          width="100">
        </el-table-column>
        <el-table-column
          property="attrName"
          label="属性名"
          width="150">
        </el-table-column>
        <el-table-column
          property="valueSelect"
          label="可选值">
        </el-table-column>
        
        <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="100"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="deleteBrandHandle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogTableVisible = false">确定</el-button>
      </span>
    </el-dialog>
     <!-- 新增关联弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible"
      width="50%"
      center>
      <el-form :inline="true" :model="attrForm" @keyup.enter.native="addRelation()">
        <el-form-item>
          <el-input v-model="attrForm.key" placeholder="参数名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="addRelation()">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="attrCategoryList" highlight-current-row  border  @selection-change="handleSelectionChange">
         <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          property="attrId"
          label="属性id"
          width="120">
        </el-table-column>
        <el-table-column
          property="attrName"
          label="属性名"
          width="180">
        </el-table-column>
        <el-table-column
          property="valueSelect"
          label="可选值列表">
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="newAddRelation">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import OssUpload from '../../components/OssUpload'
import GroupAddUpdate from './components/GroupAddUpdate'
export default {
  name: "Cate",
  data() {
    return {
      dataForm: {
          key: ''
        },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      // 批量删除的catId
      dataListSelections: [],
      // 单个删除的catId
      deleteCatId:[],
      // 当前关联的分组ID
      realtionId :'',
      // 关联弹框
      dialogTableVisible:false,
      // 新增关联弹框
      centerDialogVisible:false,
      addOrUpdateVisible: false,
      // 是否开启拖拽功能
      draggable:false,
      // 对话框提示信息
      title:'',
      // 对话框类型
      dialogType:"",
      // 添加分类数据
      category: {catId:'', name: "", parentId: 0, catLevel: 2, showStatus: 1, sort: 0 ,icon:'',productUnit:'' },
      // 商品分类展示
      goodsCategories:[],
      defaultProps: {
        children: "children",
        label: "name",
      },
      dialogFormVisible: false,
      brandCategoryList:[],
      multipleSelection: [],
      attrForm:{
         key:''
      },
      attrCategoryList:[
      ],
      //  选中是分类ID
      selectCatId:0 
    };
  },
  components:{
    OssUpload,GroupAddUpdate
  },
  created() {
    this.getGoodsCategories();
    this.getAttrList()
  },
  methods: {
    // 获取分类数据
    async  getGoodsCategories() {
      // 发获取数据请求
      const {data:res} = await this.$http.get("/dqxmall/prosyscategory/list/tree")
      // console.log(res)
      this.goodsCategories = res.data
    },
    //追加元素
    append(data) {
      // console.log("要添加的数据",data)
      this.dialogType = 'add'
      this.title = "添加分类"
      this.dialogFormVisible = true;
      this.category.parentId = data.catId
    },
    // 添加二级分类
    async  addCategory() {
      const {data:res} = await this.$http.post("/dqxmall/prosyscategory/save",this.category)
      // console.log(res)
      if(res.msg === 'success'){
        this.getGoodsCategories()
        this.$message.success("添加成功")
        this.dialogFormVisible = false;
      }
      else{
        this.$message.error("添加失败")
        this.dialogFormVisible = false;
      } 
    },
    // 修改分类
    edit(data){
      // console.log("要修改的数据",data)
      this.dialogType = 'edit'
      this.dialogFormVisible = true;
      this.title = "修改分类"
      // 重新发送送请求，获取当前节点最新数据
      this.category = data
    },
    // 修该分类请求
    async  editCategory(){
      const {data:res} = await this.$http.post("/dqxmall/prosyscategory/update",this.category)
      // console.log(res)
      if(res.msg === 'success'){
        this.getGoodsCategories()
        this.$message.success("修改成功")
        this.dialogFormVisible = false;
      }else{
        this.$message.error("修改失败")
        this.dialogFormVisible = false;
      } 
    },
    // 对话框提交
    submitData(){
      if(this.dialogType === 'add'){
        this.addCategory()
      }
      if(this.dialogType === 'edit'){
        this.editCategory()
      }
    },
    // 删除
    async  remove(node, data) {
      this.deleteCatId.push(data.catId)
      const {data:res} = await  this.$http.delete("/dqxmall/prosyscategory/delete",{data:this.deleteCatId})
        // console.log(res)
        if(res.msg === 'success'){
            this.getGoodsCategories()
            this.$message.success("删除成功")
          }
    },
    // 批量保存
    allSeve(){

    },
    //批量删除
    allDelete(){
      let checkedNodes =  this.$refs.catTree.getCheckedNodes
      // console.log(checkedNodes)
    },
    nodeClick(data,node,component){
      // console.log(data)
      this.selectCatId = data.catId
      this.getAttrList()
    },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getAttrList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getAttrList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 查询属性
      async  getAttrList(){ 
        const {data:res} = await this.$http.get(`/dqxmall/prosysattrgroup/list/${this.selectCatId}?page=${this.pageIndex}&limit=${this.pageSize}&key=${this.dataForm.key}`)
        console.log(res)
        this.dataList = res.page.list
        this.totalPage = res.page.totalCount
      },
      // 新增 / 修改
      addOrUpdateHandle (id,data) {
        this.addOrUpdateVisible = true
        // this.$nextTick 作用是当这个弹框组件完全显示后才获取数据
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id,data)
        })
      },
      // 点击关联
      relationHandle(id){
        this.realtionId  = id
        this.getRelationData()
        this.dialogTableVisible =true
      },
      // 获取关联弹框数据
      async  getRelationData(){
        const {data:res} = await this.$http.get(`/dqxmall/prosysattrgroup/${this.realtionId}/attr/relation`)
        console.log("q",res)
        this.brandCategoryList = res.data
      },
      async  addRelation(){
        this.getAddRelation()
        this.centerDialogVisible =true
      },
      // 获取新增关联弹框数据
      async  getAddRelation(){
        const {data:res} = await this.$http.get(`/dqxmall/prosysattrgroup/${this.realtionId}/noattr/relation`)
        console.log("qq",res)
        if(res.msg === 'success'){
          this.attrCategoryList = res.page.list
        }
      },
      // 
      async  newAddRelation(){
         var relationAtrrIds = this.multipleSelection.map(item => {
          return item.attrId
        });
        var relationArrs = []
          relationAtrrIds.forEach((item) =>{
            var relationArrObj = {
               attrId : item,
               attrGroupId :this.realtionId
            }
              relationArrs.push(relationArrObj)
          })
        // console.log(relationArrs)
        const {data:res}  = await this.$http.post("/dqxmall/prosysattrgroup/attr/relation",relationArrs)
        // console.log(res)
        if(res.msg === 'success'){
          this. getRelationData()
          this.$message.success("添加成功")
          this.centerDialogVisible = false
        }
      },
      // 多选框改变事件
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.attrGroupId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async() => {
          const {data:res} = await this.$http.delete("/dqxmall/prosysattrgroup/delete",{data:ids})
          // console.log(res)
          if(res.msg === 'success'){
            this.getAttrList()
            this.$message.success("删除成功")
          }
          
        })
      },
      // 添加关联中的删除
      deleteBrandHandle(data){
        this.$confirm(`确定删除该关联?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async() => {
          const {data:res} = await this.$http.post("/dqxmall/prosysattrgroup/attr/relation/delete",{
            attrId:data.attrId,
            attrGroupId: data.attrGroupId
          })
          // console.log(res)
          if(res.msg === 'success'){
            this. getRelationData()
            this.$message.success("删除成功")
          }
          
        })
      }
  },
};
</script>
<style lang="less" scoped>

</style>
